package com.kfm.am;

import java.util.Arrays;

public class Sort {

    public static void main(String[] args) {
        Student stu1 = new Student("张三", 20);
        Student stu2 = new Student("李四", 19);
        Student stu3 = new Student("王五", 18);
        Student stu4 = new Student("孙六", 23);
        Student stu5 = new Student("赵七", 22);
        Student[] students = {stu1, stu2, stu3, stu4, stu5};
//        quickSort(students, 0, students.length - 1);
//        selectSort(students);
        bubbleSort(students);
        System.out.println(Arrays.toString(students));
    }

    public static void quickSort(Student[] students, int left, int right) {
        if (left >= right) {
            return;
        }
        int i = left;
        int j = right;
        // Student stu = students[left];
        int age = students[left].getAge();
        // i 左边 从左边开始找比基准值大的停止
        // j 右边  从右边开始找比基准值小的停止
        while (i < j) {
            // i < j && students[j].getAge() >= stu.getAge()
            while (i < j && students[j].getAge() <= age) {
                j--;
            }
            while (i < j && students[i].getAge() >= age) {
                i++;
            }
            Student temp = students[i];
            students[i] = students[j];
            students[j] = temp;
        }
        if (students[i].getAge() > age) {
            Student stu = students[left];
            students[left] = students[i];
            students[i] = stu;
        }
        quickSort(students, left, i - 1);
        quickSort(students, i + 1, right);
    }

    public static void selectSort(Student[] students) {
        for (int i = 0; i < students.length; i++) {
            int index = i; // 假设本轮的第一个是最小的
            for (int j = index + 1; j < students.length; j++) {
                if (students[j].getAge() >= students[index].getAge()) {
                    index = j;
                }
            } // 本轮最小的值所在的下标
            Student stu = students[i];
            students[i] = students[index];
            students[index] = stu;
        }
    }


    public static void bubbleSort(Student[] students) {
        for (int i = 0; i < students.length - 1; i++) {
            for (int j = 0; j < students.length - i - 1; j++) {
                if (students[j].getAge() <= students[j + 1].getAge()) {
                    Student stu = students[j + 1];
                    students[j + 1] = students[j];
                    students[j] = stu;
                }
            }
        }
    }
}
